package pers.cz.postgirl.core.store;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import pers.cz.postgirl.core.Spy;
import pers.cz.postgirl.core.connect.ConnectionFactory;
import pers.cz.postgirl.core.connect.DBType;
import pers.cz.postgirl.core.connect.IConnection;
import pers.cz.postgirl.util.JefLog;
import pers.cz.postgirl.util.SerializeUtils;
import pers.cz.postgirl.util.TimeLag;

/**
 * @program: postgirl-client
 * @description: 数据库存储
 * @author: Cheng Zhi
 * @create: 2023-06-11 13:12
 **/
public class SimpleDbStore implements Store {

    private JefLog jefLog = new JefLog(SimpleDbStore.class);
    private IConnection connection;

    {
        // 初始化连接池
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connection = connectionFactory.getConnection(DBType.SIMPLEDB);
    }

    @Override
    public void set(String key, Object value) {
        // 将对象序列化
        byte[] val = SerializeUtils.serialize(value);
        connection.insert(key, val);
    }

    @Override
    public Object get(String key) {
        TimeLag timeLag = new TimeLag();
        byte[] s = connection.getBytes(key);
        Spy spy = SerializeUtils.unserialize(s);
        jefLog.debug("执行sql耗时：" + timeLag.cost());
        return spy;
    }
}
